package frame;

import dataediter.DataWR;
import main.Manager;
import main.Resource;
import other.MyImgIcon;
import other.Tool;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

/**
 * 登录窗口,包括注册窗口
 *
 * @author fdh
 */
public class LoginFrame extends FrameBase {
    private JPanel imgPanel;
    private JPanel loginPanel;
    private JLabel loginRemindJLabel;
    private MyImgIcon img1;
    private Point imgPanelPos = Resource.LoginFrameResource.imgPanelPos;
    private Point loginPanelPoint = new Point();
    private JTextField loginUsernameInput;
    private JTextField loginPasswordInput;
    private JButton loginBtnMain;
    private JButton registerBtnMain;
    private JLabel welcomeTxt;
    private JLabel usernameTxt;
    private JLabel passwordTxt;
    private JLabel authorJLabel;

    public LoginFrame() {
        super();
        frame.setTitle(Resource.LoginFrameResource.titleTxt);
        frame.setSize(Resource.LoginFrameResource.frameSize);
        imgPanel = iniImgPanel();
        loginPanel = iniLoginPanel();
        frame.add(imgPanel);
        frame.add(loginPanel);
        setImgPanel();
        setLoginPanel();
        frame.setVisible(true);
        super.iniFrameListener();
    }

    /**
     * 初始化左边的图片面板
     *
     * @return
     */
    private JPanel iniImgPanel() {
        JPanel imgPanel = new JPanel();
        changePanelSize(imgPanel, Resource.LoginFrameResource.imgPanelRatio, imgPanelPos);
        // imgPanel.setBackground(Color.red);
        return imgPanel;
    }

    private void setImgPanel() {
        addImg();
    }

    /**
     * 初始化右边的登录面板
     *
     * @return
     */
    private JPanel iniLoginPanel() {
        JPanel loginPanel = new JPanel();
        loginPanel.setLayout(null);
        changePanelSize(loginPanel, Resource.LoginFrameResource.loginPanelRatio, new Point(imgPanel.getWidth(), 0));
//        loginPanel.setBackground(Color.blue);
        return loginPanel;
    }

    private void setLoginPanel() {
        welcomeTxt = Tool.getInstance().getSongTiJLabel(Resource.LoginFrameResource.welcomeTxt, 20);
        usernameTxt = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.usernameTxt, 15);
        passwordTxt = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.loginBtnTxt, 15);
        authorJLabel = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.authorTxt, 10);
        loginRemindJLabel = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.remindTxt, 10);
        loginUsernameInput = new JTextField();
        loginPasswordInput = new JTextField();
        loginBtnMain = new JButton(Resource.LoginFrameResource.loginBtnTxt);
        registerBtnMain = new JButton(Resource.LoginFrameResource.registerBtnTxt);
        loginPanel.add(welcomeTxt);
        loginPanel.add(usernameTxt);
        loginPanel.add(passwordTxt);
        loginPanel.add(loginUsernameInput);
        loginPanel.add(loginPasswordInput);
        loginPanel.add(loginBtnMain);
        loginPanel.add(registerBtnMain);
        loginPanel.add(loginRemindJLabel);
        loginPanel.add(authorJLabel);
        setLoginBtn();
        setRegisterDialog();
    }

    private void setRegisterDialog() {
        registerBtnMain.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(frame, "注册", true);
                dialog.setLayout(null);
                dialog.setSize(400, 300);
                JLabel usernameLabel = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.usernameTxt, 15);
                JLabel passwordLabel = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.passwordTxt, 15);
                JLabel rePasswordLabel = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.rePasswordTxt, 15);
                JLabel reminderJLabel = Tool.getInstance().getMSYaHeiJLabel(Resource.LoginFrameResource.remindTxt, 10);
                JTextField usernameInput = new JTextField();
                JTextField passwordInput = new JTextField();
                JTextField rePasswordInput = new JTextField();
                JButton registerbtn = new JButton(Resource.LoginFrameResource.registerBtnTxt);
                int width1 = (int) (dialog.getWidth() * 0.2);
                int width2 = (int) (dialog.getWidth() * 0.6);
                usernameLabel.setBounds(Resource.LoginFrameResource.offsetPos, 10, width1, 30);
                passwordLabel.setBounds(Resource.LoginFrameResource.offsetPos, 50, width1, 30);
                rePasswordLabel.setBounds(Resource.LoginFrameResource.offsetPos, 90, width1, 30);
                usernameInput.setBounds(Resource.LoginFrameResource.offsetPos + width1, 10, width2, 30);
                passwordInput.setBounds(Resource.LoginFrameResource.offsetPos + width1, 50, width2, 30);
                rePasswordInput.setBounds(Resource.LoginFrameResource.offsetPos + width1, 90, width2, 30);
                registerbtn.setBounds(dialog.getWidth() / 2 - width1, 130, width1, 30);
                reminderJLabel.setBounds(Resource.LoginFrameResource.offsetPos, 170, dialog.getWidth(), 30);
                dialog.add(usernameLabel);
                dialog.add(passwordLabel);
                dialog.add(rePasswordLabel);
                dialog.add(usernameInput);
                dialog.add(passwordInput);
                dialog.add(rePasswordInput);
                dialog.add(registerbtn);
                dialog.add(reminderJLabel);
                registerbtn.addActionListener(e1 -> {
                    String username = usernameInput.getText();
                    String password = passwordInput.getText();
                    String rePassword = rePasswordInput.getText();
                    if (username.isEmpty() || password.isEmpty() || rePassword.isEmpty()) {
                        return;
                    }
                    if (!Tool.getInstance().isLetterOrDigitOrUnderLine(username) || !Tool.getInstance().isLetterOrDigitOrUnderLine(password) || !Tool.getInstance().isLetterOrDigitOrUnderLine(rePassword)) {
                        reminderJLabel.setText(Resource.LoginFrameResource.haveNotEnableChar);
                        return;
                    }
                    if (username.length() < Resource.LoginFrameResource.usernameLength[0] || username.length() > Resource.LoginFrameResource.usernameLength[1] || password.length() < Resource.LoginFrameResource.passwordLength[0] || password.length() > Resource.LoginFrameResource.passwordLength[1]) {
                        reminderJLabel.setText(Resource.LoginFrameResource.infoLengthError);
                        return;
                    }
                    if (!password.equals(rePassword)) {
                        reminderJLabel.setText(Resource.LoginFrameResource.rePasswordError);
                        return;
                    }
                    System.out.println("开始写入用户数据:" + username + " " + password);
//                    new DataWRBase().write(main.Resource.LoginFrameResource.userInfoSrc, new DataWRBase.WriteInfo() {
//                        @Override
//                        public boolean search(String line) {
//                            return line.contains(main.Resource.DataFile.UserInfo.userInfoEnd);
//                        }
//
//                        @Override
//                        public String write() {
//                            return username + "," + password;
//                        }
//                    });
                    DataWR dataWR;
                    try {
                        dataWR = new DataWR(Resource.LoginFrameResource.userInfoSrc);
                        if (dataWR.haveData(Resource.DataFile.UserInfo.userInfoStart, Resource.DataFile.UserInfo.userInfoEnd, new DataWR.SearchData() {
                            @Override
                            public boolean search(String line) {
                                return line.split(",")[0].equals(username);
                            }
                        })) {
                            reminderJLabel.setText("用户名重复");
                            return;
                        }
                        dataWR.writeToFile(username + "," + password, Resource.DataFile.UserInfo.userInfoEnd);
                    } catch (Exception ex) {
                        System.out.println(ex.getMessage());
                    }
                    dialog.dispose();
                });
                dialog.setVisible(true);
            }
        });
    }

    private void setLoginBtn() {
        loginBtnMain.addActionListener(e -> {
            String username = loginUsernameInput.getText();
            String password = loginPasswordInput.getText();
            if (username.isEmpty() || password.isEmpty()) {
                return;
            }
            if (!Tool.getInstance().isLetterOrDigitOrUnderLine(username) || !Tool.getInstance().isLetterOrDigitOrUnderLine(password)) {
                JOptionPane.showConfirmDialog(frame, Resource.LoginFrameResource.haveNotEnableChar, "登录失败", JOptionPane.DEFAULT_OPTION);
                return;
            }
            if (username.length() < Resource.LoginFrameResource.usernameLength[0] || username.length() > Resource.LoginFrameResource.usernameLength[1] || password.length() < Resource.LoginFrameResource.passwordLength[0] || password.length() > Resource.LoginFrameResource.passwordLength[1]) {
                JOptionPane.showConfirmDialog(frame, Resource.LoginFrameResource.infoLengthError, "登录失败", JOptionPane.DEFAULT_OPTION);
                return;
            }
            System.out.println("开始读取用户数据:" + username + " " + password);
            boolean isSuccessful = false;
            try {
                isSuccessful = new DataWR(Resource.LoginFrameResource.userInfoSrc).haveData(Resource.DataFile.UserInfo.userInfoStart, Resource.DataFile.UserInfo.userInfoEnd, new DataWR.SearchData() {
                    @Override
                    public boolean search(String line) {
                        return line.equals(username + "," + password);
                    }
                });
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            if (isSuccessful) {
                System.out.println("登录成功");
                super.destroy();
                Manager.getInstance().setPage(Manager.AllPage.indexPage);
            } else {
                JOptionPane.showConfirmDialog(frame, "用户名或密码错误", "登录失败", JOptionPane.DEFAULT_OPTION);
            }
        });
    }

    @Override
    protected void selfAdaption() {
        changePanelSize(imgPanel, Resource.LoginFrameResource.imgPanelRatio, imgPanelPos);
        loginPanelPoint.setLocation(imgPanel.getWidth(), 0);
        changePanelSize(loginPanel, Resource.LoginFrameResource.loginPanelRatio, loginPanelPoint);
        img1.changeImgSize();
        changeLoginPanelItem();
    }

    private void changeLoginPanelItem() {
        int width1 = (int) (loginPanel.getWidth() * 0.2);
        int width2 = (int) (loginPanel.getWidth() * 0.6);
        welcomeTxt.setBounds(Resource.LoginFrameResource.offsetPos, 20, loginPanel.getWidth(), 30);
        usernameTxt.setBounds(Resource.LoginFrameResource.offsetPos, 60, width1, 30);
        passwordTxt.setBounds(Resource.LoginFrameResource.offsetPos, 100, width1, 30);
        loginUsernameInput.setBounds(Resource.LoginFrameResource.offsetPos + width1, 60, width2, 30);
        loginPasswordInput.setBounds(Resource.LoginFrameResource.offsetPos + width1, 100, width2, 30);
        loginBtnMain.setBounds(Resource.LoginFrameResource.offsetPos, 150, width1 + 20, 40);
        registerBtnMain.setBounds(Resource.LoginFrameResource.offsetPos + width1 + 30, 150, width1 + 20, 40);
        loginRemindJLabel.setBounds(Resource.LoginFrameResource.offsetPos, 200, loginPanel.getWidth(), 30);
        authorJLabel.setBounds(Resource.LoginFrameResource.offsetPos, loginPanel.getHeight() - 70, width2, 30);
    }

    private void changePanelSize(JPanel panel, double scale, Point pos) {
        panel.setLocation(pos);
        panel.setSize((int) (frame.getWidth() * scale), frame.getHeight());
    }

    private void addImg() {
        img1 = new MyImgIcon(Resource.LoginFrameResource.currentLoginImgSrc, MyImgIcon.ShowType.Fill, imgPanel);
        JLabel imgLabel = new JLabel(img1);
        imgPanel.add(imgLabel);
    }
}